<script setup lang="ts">
import { ref } from 'vue'

const length = ref(12)
const useLower = ref(true)
const useUpper = ref(true)
const useNumbers = ref(true)
const useSymbols = ref(true)
const password = ref('')

function generate() {
  let charset = ''
  if (useLower.value) charset += 'abcdefghijklmnopqrstuvwxyz'
  if (useUpper.value) charset += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
  if (useNumbers.value) charset += '0123456789'
  if (useSymbols.value) charset += '!@#$%^&*()_+-={}[]|:;<>,.?/'
  if (!charset) {
    alert('请至少选择一种字符集')
    return
  }
  const array = new Uint32Array(length.value)
  crypto.getRandomValues(array)
  password.value = Array.from(array, (v) => charset[v % charset.length]).join('')
}

async function copy() {
  if (!password.value) return
  try {
    await navigator.clipboard.writeText(password.value)
    alert('已复制到剪贴板')
  } catch {
    alert('复制失败，请手动选择复制')
  }
}
</script>

<template>
  <div class="space-y-4">
    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
      <div>
        <label class="block text-sm font-medium mb-1">长度：{{ length }}</label>
        <input type="range" min="6" max="64" v-model.number="length" />
      </div>
      <div class="grid grid-cols-2 gap-2">
        <label class="flex items-center gap-2"><input type="checkbox" v-model="useLower" /> 小写字母</label>
        <label class="flex items-center gap-2"><input type="checkbox" v-model="useUpper" /> 大写字母</label>
        <label class="flex items-center gap-2"><input type="checkbox" v-model="useNumbers" /> 数字</label>
        <label class="flex items-center gap-2"><input type="checkbox" v-model="useSymbols" /> 符号</label>
      </div>
    </div>
    <div class="flex items-center gap-2">
      <input
        :value="password"
        readonly
        class="flex-1 p-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700"
      />
      <button class="px-3 py-2 bg-primary text-white rounded hover:bg-primary/90" @click="generate">生成</button>
      <button class="px-3 py-2 bg-gray-200 dark:bg-gray-700 rounded hover:bg-gray-300 dark:hover:bg-gray-600" @click="copy">复制</button>
    </div>
  </div>
</template>

<style scoped></style>